package com.sx.medicinecard.common;

import com.aliyun.openservices.log.exception.LogException;
import com.google.protobuf.ServiceException;
import javax.servlet.http.HttpServletRequest;

import com.sx.medicinecard.exception.UnauthorizedException;
import io.jsonwebtoken.JwtException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.nio.file.AccessDeniedException;
import java.util.HashMap;
import java.util.Map;

/**
 * 异常处理 配置
 *
 * @author javadog
 */
@RestControllerAdvice
public class GlobalException {

    private static final Logger log = LoggerFactory.getLogger(GlobalException.class);

    /**
     * 权限校验异常
     */
    @ExceptionHandler(AccessDeniedException.class)
    public ResponseResult handleAccessDeniedException(AccessDeniedException e, HttpServletRequest request) {
        String requestURI = request.getRequestURI();
        log.error("请求地址'{}',权限校验失败'{}'", requestURI, e.getMessage());
        return ResponseResult.error(HttpStatusEnum.FORBIDDEN.getCode(), HttpStatusEnum.FORBIDDEN.getMessage());
    }

    /**
     * 权限校验异常
     */
    @ExceptionHandler(UnauthorizedException.class)
    public ResponseResult handleUnauthorizedException(UnauthorizedException e, HttpServletRequest request) {
        String requestURI = request.getRequestURI();
        log.error("请求地址'{}',权限校验失败'{}'", requestURI, e.getMessage());
        return ResponseResult.error(HttpStatusEnum.UNAUTHORIZED.getCode(),"权限不足");
    }

    /**
     * 参数校验失败
     * @param e
     * @param request
     * @return
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public Map<String, String> handleValidationExceptions(MethodArgumentNotValidException e, HttpServletRequest request) {
        Map<String, String> errors = new HashMap<>();
        log.error("请求地址'{}',参数校验失败'{}'", request.getRequestURI(), e.getMessage());
        e.getBindingResult().getFieldErrors().forEach(error ->
                errors.put(error.getField(), error.getDefaultMessage()));
        return errors;
    }

/*
    */
/**6
     * 请求方式不支持
     *//*

    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    public ResponseResult handleHttpRequestMethodNotSupported(HttpRequestMethodNotSupportedException e,
                                                              HttpServletRequest request) {
        String requestURI = request.getRequestURI();
        log.error("请求地址'{}',不支持'{}'请求", requestURI, e.getMethod());
        return ResponseResult.fail(e.getMessage());
    }

     * 系统异常
     *//*

    @ExceptionHandler(Exception.class)
    public ResponseResult handleException(Exception e, HttpServletRequest request) {
        String requestURI = request.getRequestURI();
        log.error("请求地址'{}',发生系统异常.", requestURI, e);
        return ResponseResult.fail(e.getMessage());
    }

*/
/*    *//*
*/
/**
     * 自定义验证异常
     *//*
*/
/*
    @ExceptionHandler(BindException.class)
    public ResponseResult handleBindException(BindException e) {
        log.error(e.getMessage(), e);
        String message = e.getAllErrors().get(0).getDefaultMessage();
        return ResponseResult.fail(message);
    }*//*


    */
/**
     * 自定义验证异常
     *//*

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Object handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        log.error(e.getMessage(), e);
        String message = e.getBindingResult().getFieldError().getDefaultMessage();
        return ResponseResult.fail(message);
    }
*/

/*    @ExceptionHandler(BadCredentialsException.class)
    public ResponseResult handleBadCredentialsException(BadCredentialsException e) {
        log.error(e.getMessage(), e);
        String message = e.getMessage();
        return ResponseResult.error(HttpStatusEnum.PASSWORD_WRONG.getCode(), message);
    }*/

    /**
     * 业务异常
     */
    @ExceptionHandler(ServiceException.class)
    public ResponseResult handleServiceException(ServiceException e, HttpServletRequest request) {
        String requestURI = request.getRequestURI();
        log.error("请求地址'{}',发生业务异常.", requestURI, e);
        return ResponseResult.error(HttpStatusEnum.WARN.getCode(), e.getMessage());
    }
    /**
     * 阿里日志服务异常
     */
    @ExceptionHandler(LogException.class)
    public ResponseResult handleServiceException(LogException e, HttpServletRequest request) {
        String requestURI = request.getRequestURI();
        log.error("请求地址'{}',阿里日志服务异常.", requestURI, e);
        return ResponseResult.error(HttpStatusEnum.WARN.getCode(), e.getMessage());
    }

    /**
     * 拦截未知的运行时异常
     */
    @ExceptionHandler(RuntimeException.class)
    public ResponseResult handleRuntimeException(RuntimeException e, HttpServletRequest request) {
        String requestURI = request.getRequestURI();
        log.error("请求地址'{}',发生未知异常.", requestURI, e);
        return ResponseResult.error(HttpStatusEnum.WARN.getCode(),e.getMessage());
    }

    /**
     * Jwt异常
     */
    @ExceptionHandler(JwtException.class)
    public ResponseResult handleJwtException(JwtException e, HttpServletRequest request) {
        log.error("请求地址：'{}',Jwt异常：'{}'", request.getRequestURI(), e.getMessage());
        return ResponseResult.error(HttpStatusEnum.FORBIDDEN.getCode(),HttpStatusEnum.FORBIDDEN.getMessage());
    }

}